package com.iflytek.jcy.supervise.job.component.web.filter;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2022/6/15
 */
@Configuration
public class ResponseReplaceFilterConfig {

    @Value("${replace.urls:}")
    private String[] replaceFdfsUrls;
    @Value("${replace.old:}")
    private String replaceOld;
    @Value("${replace.new:}")
    private String replaceNew;

    @Bean
    @ConditionalOnExpression("'${replace.enable}'.equals('true')")
    public FilterRegistrationBean registrationFdfsReplaceFilter() {
        // 替换响应体内容, 替换时机为JSON序列化完成, 在向响应体写数据之前
        FilterRegistrationBean<ResponseReplaceFilter> bean = new FilterRegistrationBean<>();
        bean.setOrder(1);
        bean.setFilter(new ResponseReplaceFilter(replaceOld, replaceNew));
        // url格式: /test 或 /user/*
        if (ArrayUtils.isNotEmpty(replaceFdfsUrls)) {
            for (String url : replaceFdfsUrls) {
                bean.addUrlPatterns(url);
            }
        }
        return bean;
    }
}
